import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

/**
 * Created by forcht on 2018/5/21.
 */
public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        ArrayList<Integer> curList = new ArrayList<>();
        Arrays.sort(candidates);
        dfs(list, curList, candidates,target , 0,0);
        return list;
    }

    public void dfs(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> curList, int[] candidates, int target, int sum,int cur) {
        if (sum == target) {
            ArrayList<Integer> clone = (ArrayList<Integer>)curList.clone();
            list.add(clone);
            return;
        }
        for (int i = cur; i < candidates.length; i++) {
            if (sum + candidates[i] <= target) {
                curList.add(candidates[i]);
                dfs(list, curList, candidates, target, sum + candidates[i],i);
                curList.remove(curList.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] a = {8,7,4,3};
        System.out.println(solution.combinationSum(a, 11));
    }
}
